package com.craftcomputing.client;

import com.craftcomputing.client.Entry.*;
import com.craftcomputing.client.Listeners.SearchResultListeners.*;
import com.craftcomputing.client.Pages.WebPage;
import com.craftcomputing.client.SearchResult.CodeSearchResult;
import com.google.gwt.core.client.*;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
import com.google.gwt.user.client.ui.*;
import org.gwtwidgets.client.util.WindowUtils;
import com.google.gwt.user.client.HTTPRequest;
import java.util.*;

public class MainPage implements EntryPoint, HistoryListener{
	static private WebPage page = new WebPage();
	static private int historyItemNum = 0;
	static private HashMap historyMap = new HashMap();
	private EntryPanel entry;		
	public void onModuleLoad() {
		loadEntryFromURL();

		RootPanel rootPanel = RootPanel.get();
		//rootPanel.setWidth("700px");
		rootPanel.add(page);
		page.add(entry);
		
	    String initToken = History.getToken();
	    if(initToken.length() != 0)
	    	onHistoryChanged(initToken);
	    History.addHistoryListener(this);
	}	
	public void onHistoryChanged(String historyToken) {
		Composite panel = (Composite)historyMap.get(historyToken);
		if(panel != null){
			page.clear();
			page.add(panel);			
		}
	}
	static public void setMainPanel(Composite mainPanel){
		String key = "foo" + historyItemNum++;
		History.newItem(key);
		historyMap.put(key, mainPanel);
		page.clear();
		page.add(mainPanel);
	}
	public void loadEntryFromURL(){
		String workshopId = WindowUtils.getLocation().getParameter("workshopId");
		if(workshopId != null)
			makeNewEntry(new WorkshopEntry(), workshopId);
		String codeId = WindowUtils.getLocation().getParameter("codeId");
		if(codeId != null)
			makeNewEntry(new CodeEntry(), codeId);
		if((workshopId == null) && (codeId == null))
			entry = new IntroEntry();
	}
	public void makeNewEntry(EntryPanel entry, String id){
		this.entry = entry;
		//String searchText = "/python/codesample?codeId=" + id;
		String searchText = "/python/workshop?workshopId=" + id;
		HTTPRequest.asyncGet(searchText, new JSONEntryFetchTextHandler(entry));
	}
}
